package com.village.friend.utils;

import com.village.friend.constant.ChatWords;
import com.village.friend.constant.PayStatus;
import com.village.friend.constant.PolicyType;
import com.village.friend.entity.User;
import com.village.friend.entity.UserOrder;
import com.village.friend.entity.UserPolicy;
import com.village.friend.service.OpenImService;
import com.village.friend.service.UserOrderService;
import com.village.friend.service.UserPolicyService;
import com.village.friend.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Random;

public class OrderUtils {
    private static final Logger log = LoggerFactory.getLogger(OrderUtils.class);

    /**
     * 生成订单信息
     *
     * @param user        用户信息
     * @param channelName 支付渠道
     * @param id          订单id
     * @param business    交易类型
     * @param orderPrice  订单金额
     * @param productName 产品名称
     * @param payStatus   订单状态
     * @return
     */
    public static UserOrder genOrder(User user, String channelName, String id, PolicyType business,
                                     BigDecimal orderPrice, String productName, PayStatus payStatus) {
        UserOrder tradePaymentOrder = new UserOrder();
        tradePaymentOrder.setId(id);
        if (user == null) {
            throw new RuntimeException("用户信息不能为空");
        }
        tradePaymentOrder.setParent(user.getParent());
        tradePaymentOrder.setUserId(user.getUid());
        tradePaymentOrder.setName(user.getName());
        tradePaymentOrder.setParent(user.getParent());
        tradePaymentOrder.setProductName(productName);
        //订单金额不为空 或者 > 0
        if (orderPrice == null || orderPrice.doubleValue() <= 0) {
            throw new RuntimeException("订单金额错误");
        }
        tradePaymentOrder.setOrderAmount(orderPrice);// 订单总金额
        tradePaymentOrder.setPayStatus(payStatus.getValue());
        tradePaymentOrder.setOrderPeriod(120);//有效期120分钟
        tradePaymentOrder.setExpireTime(LocalDateTime.now().plusHours(2));
        tradePaymentOrder.setPayWayName(channelName);
        tradePaymentOrder.setSplitFlag("0");
        tradePaymentOrder.setReconFlag("0");
        tradePaymentOrder.setPayTypeNo(business.getType());
        tradePaymentOrder.setPayTypeName(business.getName());

        return tradePaymentOrder;
    }


    public static String getOrderNo(String pro) {
        String val = "";
        Random random = new Random();
        //参数length，表示生成几位随机数
        for (int i = 0; i < 9; i++) {
            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
            //输出字母还是数字
            if ("char".equalsIgnoreCase(charOrNum)) {
                //输出是大写字母还是小写字母
                int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
                val += (char) (random.nextInt(26) + temp);
            } else if ("num".equalsIgnoreCase(charOrNum)) {
                val += String.valueOf(random.nextInt(10));
            }
        }

        return pro + System.currentTimeMillis() + val;
    }

    /**
     * 除法
     */
    public static BigDecimal divide(String arg1, String arg2) {
        if (StringUtils.isEmpty(arg1)) {
            arg1 = "0.0";
        }
        if (StringUtils.isEmpty(arg2)) {
            arg2 = "0.0";
        }
        BigDecimal big3 = new BigDecimal("0.00");
        if (Double.parseDouble(arg2) != 0) {
            BigDecimal big1 = new BigDecimal(arg1);
            BigDecimal big2 = new BigDecimal(arg2);
            big3 = big1.divide(big2, 2, BigDecimal.ROUND_HALF_EVEN);
        }
        return big3;
    }


    /**
     * 支付状态改变
     *
     * @param orderNo
     * @param transAmount
     * @param status
     */
    public static void payStatusChange(UserOrderService orderService, UserService userService, UserPolicyService policyService, OpenImService openImService, String orderNo, BigDecimal transAmount, PayStatus status) {
        UserOrder order = orderService.getById(orderNo);
        if (order == null) {
            RuntimeException error = new RuntimeException("订单不存在:" + orderNo);
            log.error("订单不存在", error);
            throw error;
        }
        //更新订单状态
        if (!status.getValue().equalsIgnoreCase(order.getPayStatus())) {
            order.setPayStatus(status.getValue());
            orderService.updateById(order);
        }
        //更新用户等级
        if (status == PayStatus.SUCCESS && PolicyType.UPGRADE.getType().equalsIgnoreCase(order.getPayTypeNo())) {
            //更新用户等级
            User user = userService.getById(order.getUserId());
            UserPolicy policy = policyService.findOneByTypeAndPrice(PolicyType.UPGRADE.getType(), transAmount.intValue());
            if (policy == null) {
                throw new RuntimeException("用户缴费配置不存在:" + transAmount);
            }
            LocalDateTime vipEnd = user.getVipEnd();
            if (vipEnd == null || vipEnd.isBefore(LocalDateTime.now())) {
                vipEnd = LocalDateTime.now();
            }
            LocalDateTime vipEndNew = vipEnd.plusMonths(Integer.valueOf(policy.getMonths()));
            userService.updateVipByUid(order.getUserId(), policy.getVipLevel(), vipEndNew);

            openImService.sendMsgByManager(order.getUserId(), ChatWords.ADD_VIP_SUCCESS);
        }
    }

}
